import { memo, useEffect, useRef, useState } from "react";
import type { FC } from "react";
import {
  StyleProvider,
  legacyLogicalPropertiesTransformer,
} from "@ant-design/cssinjs";
// import Form from 'rc-field-form'
import { useSetState } from "ahooks";
import { AutoComplete, Button, Form, Input, Radio, Select, Space } from "antd";
import { DeleteOutlined } from "@ant-design/icons";
import contentStyle from "../../index.module.scss";
import styles from "./index.module.scss";
import Avator from "./avator";

import { getMonth, getYear } from "@/app/utils";
import {
  PersonalConst,
  arrivalTime,
  gender,
  politicsStatus,
  workingYears,
} from "@/cvcomponents/common/utils";
import { usePersonalDetailStore } from "@/src/providers/personal-detail-store-provider";
import { useCommonStore } from "@/src/providers/common-store-provider";
import useServerStore from "@/app/components/hooks/useServerStore";
import BottomButton from "@/app/components/BottomButton";

interface IndexProps {}

const items = Object.keys(PersonalConst).filter(
  (item) => item !== "name" && item !== "expJob"
) as (keyof PersonalDetails)[];

function PhotoFormItem(props) {
  const { value, onChange } = props;
  const { showPhoto, photo } = value || {};
  return (
    <div style={{ position: "relative", cursor: "pointer" }}>
      <Avator
        photo={photo}
        showPhoto={showPhoto}
        changeShowPhoto={(e: any) => {
          onChange({ ...value, showPhoto: e });
        }}
        photoChange={(url: string) => {
          onChange({ ...value, photo: url });
        }}
      />
    </div>
  );
}

const Index: FC<IndexProps> = () => {
  const { updateDetail, personalDetails, updateDetailOrder } =
    usePersonalDetailStore((state) => state);
  const { setCurrentTab } = useCommonStore((state) => state);
  const oldPersonalDetails = useRef(null);
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);

  const [state, setState] = useSetState<{
    months: any[];
    years: any[];
    displayItems: (keyof PersonalDetails)[];
    canSelectedItems: (keyof PersonalDetails)[];
  }>({
    months: [],
    years: [],
    displayItems: [],
    canSelectedItems: [],
  });
  const serverStore = useServerStore();
  useEffect(() => {
    oldPersonalDetails.current = {
      ...personalDetails,
      detailsOrder: [...(personalDetails.detailsOrder || [])],
    };
    form.setFieldsValue({
      ...personalDetails,
      birthDay: personalDetails.birthDay || {
        year: undefined,
        month: undefined,
      },
    });
    setState({ months: getMonth(12), years: getYear(80) });
    const siderbar = document.getElementById("siderbar");
    if (siderbar) {
      siderbar.style.display = "none";
    }
  }, []);
  useEffect(() => {
    const map = personalDetails.detailsOrder?.reduce((o, n) => {
      o.add(n);
      return o;
    }, new Set(["name", "expJob"]));
    setState({
      displayItems: items.filter((v) => map?.has(v)),
      canSelectedItems: items.filter((v) => !map?.has(v)),
    });
  }, [personalDetails]);
  const onRemove = (key: any) => {
    const detailsOrder = personalDetails.detailsOrder || [];
    const index = detailsOrder?.findIndex((d) => d === key);
    let deleted: any = "";
    if (index != null && index !== -1) {
      [deleted] = detailsOrder?.splice(index, 1);
    }

    const obj = { ...personalDetails, detailsOrder };
    if (deleted === "birthDay") {
      obj.showAge = false;
    }
    obj[deleted] = null;
    form.setFieldValue(deleted, null);
    updateDetail(obj);
  };
  const onChangeCurrent = () => {
    setCurrentTab("content");
  };
  const reset = () => {
    updateDetail({ ...oldPersonalDetails.current });
  };
  return (
    <StyleProvider
      transformers={[legacyLogicalPropertiesTransformer]}
      hashPriority="high"
    >
      <div className={styles.personalDetailEdit}>
        <div className={contentStyle.card} style={{ overflow: "hidden" }}>
          <Form
            layout="vertical"
            form={form}
            onValuesChange={(value, values) => {
              const formDetail = { ...personalDetails };

              if (value.birthDay) {
                updateDetail({ ...formDetail, birthDay: values.birthDay });
              } else if (value.weightHeight) {
                updateDetail({
                  ...formDetail,
                  weightHeight: values.weightHeight,
                });
              } else {
                updateDetail({ ...formDetail, ...value });
              }
            }}
          >
            {/* <Form.Item name={'photoObj'} style={{ marginTop: '10px', display: 'flex', justifyContent: 'center' }}>
          <PhotoFormItem />
        </Form.Item> */}
            <div
              style={{
                margin: "10px 10px 20px",
                fontWeight: "bold",
                fontSize: "16px",
              }}
            >
              个人信息
            </div>
            <div style={{ display: "flex", gap: "20px" }}>
              <div style={{ flex: 1 }}>
                <Form.Item
                  name={"name"}
                  label={"姓　　名"}
                  rules={[{ required: true, message: "姓名必填" }]}
                >
                  <Input allowClear></Input>
                </Form.Item>
                <Form.Item name={"expJob"} label={"求职岗位"}>
                  <Input allowClear></Input>
                </Form.Item>
              </div>
              <Form.Item
                name={"photoObj"}
                style={{
                  marginTop: "10px",
                  display: "flex",
                  justifyContent: "center",
                }}
              >
                <PhotoFormItem />
              </Form.Item>
            </div>
            {state.displayItems?.map((key) => {
              if (key === "workingYears") {
                return (
                  <Form.Item key={key} label="工作年限">
                    <Space.Compact block>
                      <Form.Item name={"workingYears"} noStyle>
                        <AutoComplete
                          allowClear
                          options={workingYears}
                          style={{ width: "100%" }}
                        />
                      </Form.Item>
                      <Button
                        icon={<DeleteOutlined style={{ color: "red" }} />}
                        onClick={() => {
                          onRemove(key);
                        }}
                      ></Button>
                    </Space.Compact>
                  </Form.Item>
                );
              }
              if (key === "politicsStatus") {
                return (
                  <Form.Item key={key} label="政治面貌">
                    <Space.Compact block>
                      <Form.Item name={"politicsStatus"} noStyle>
                        <AutoComplete
                          allowClear
                          options={politicsStatus}
                          style={{ width: "100%" }}
                        />
                      </Form.Item>
                      <Button
                        icon={<DeleteOutlined style={{ color: "red" }} />}
                        onClick={() => {
                          onRemove(key);
                        }}
                      ></Button>
                    </Space.Compact>
                  </Form.Item>
                );
              }
              if (key === "birthDay") {
                return (
                  <div key={key}>
                    <Form.Item key={key} label="出生日期">
                      <Space.Compact block>
                        <Space.Compact block>
                          <Form.Item name={["birthDay", "year"]} noStyle>
                            <Select allowClear options={state.years}></Select>
                          </Form.Item>
                          <Form.Item name={["birthDay", "month"]} noStyle>
                            <Select allowClear options={state.months}></Select>
                          </Form.Item>
                        </Space.Compact>
                        <Button
                          icon={<DeleteOutlined style={{ color: "red" }} />}
                          onClick={() => {
                            onRemove(key);
                          }}
                        ></Button>
                      </Space.Compact>
                    </Form.Item>
                    <div style={{ overflow: "hidden" }}>
                      <Form.Item
                        name={"showAge"}
                        style={{
                          float: "right",
                          marginRight: "30px",
                          marginTop: "10px",
                        }}
                      >
                        <Radio.Group>
                          <Radio value={false}>生日</Radio>
                          <Radio value={true}>年龄</Radio>
                        </Radio.Group>
                      </Form.Item>
                    </div>
                  </div>
                );
              }
              if (key === "gender") {
                return (
                  <Form.Item key={key} label="性 别">
                    <Space.Compact block>
                      <Form.Item name={"gender"} noStyle>
                        <Select allowClear options={gender}></Select>
                      </Form.Item>
                      <Button
                        icon={<DeleteOutlined style={{ color: "red" }} />}
                        onClick={() => {
                          onRemove(key);
                        }}
                      ></Button>
                    </Space.Compact>
                  </Form.Item>
                );
              }
              if (key === "weightHeight") {
                return (
                  <Form.Item key={key} label="身高/体重">
                    <Space.Compact block>
                      <Space.Compact block>
                        <Form.Item name={["weightHeight", "height"]} noStyle>
                          <Input
                            allowClear
                            addonAfter={<div style={{ width: "25px" }}>cm</div>}
                          ></Input>
                        </Form.Item>
                        <Form.Item name={["weightHeight", "weight"]} noStyle>
                          <Input
                            allowClear
                            addonAfter={<div style={{ width: "25px" }}>kg</div>}
                          ></Input>
                        </Form.Item>
                      </Space.Compact>
                      <Button
                        icon={<DeleteOutlined style={{ color: "red" }} />}
                        onClick={() => {
                          onRemove(key);
                        }}
                      ></Button>
                    </Space.Compact>
                  </Form.Item>
                );
              }
              if (key === "arrivalTime") {
                return (
                  <Form.Item key={key} label={PersonalConst[key]}>
                    <Space.Compact block>
                      <Form.Item name={key} noStyle>
                        <AutoComplete
                          allowClear
                          options={arrivalTime}
                          style={{ width: "100%" }}
                        />
                      </Form.Item>
                      <Button
                        icon={<DeleteOutlined style={{ color: "red" }} />}
                        onClick={() => {
                          onRemove(key);
                        }}
                      ></Button>
                    </Space.Compact>
                  </Form.Item>
                );
              }
              return (
                <Form.Item
                  key={key}
                  label={PersonalConst[key]}
                  required={key === "name"}
                >
                  <Space.Compact block>
                    <Form.Item
                      name={key}
                      rules={
                        key === "name"
                          ? [{ required: true, message: "姓名必填" }]
                          : []
                      }
                      noStyle
                    >
                      <Input allowClear></Input>
                    </Form.Item>
                    {key !== "name" &&
                    key !== "email" &&
                    key !== "phoneNumber" &&
                    key !== "expJob" ? (
                      <Button
                        icon={<DeleteOutlined style={{ color: "red" }} />}
                        onClick={() => {
                          onRemove(key);
                        }}
                      ></Button>
                    ) : null}
                  </Space.Compact>
                </Form.Item>
              );
            })}

            <Form.Item name={"id"} hidden>
              <Input allowClear></Input>
            </Form.Item>
          </Form>
          <div className={styles.infoWraper}>
            {state.canSelectedItems.map((item) => {
              return (
                <div
                  className={styles.item}
                  key={item}
                  onClick={() => {
                    const detailsOrder = personalDetails.detailsOrder || [];
                    detailsOrder?.push(item);
                    updateDetailOrder(detailsOrder);
                  }}
                >
                  <svg
                    style={{ width: "15px", marginRight: "4px" }}
                    xmlns="http://www.w3.org/2000/svg"
                    viewBox="0 0 19 19"
                    fill="currentColor"
                    className="w-[1.4em]"
                  >
                    <path
                      fillRule="evenodd"
                      d="M10.8 2.452a1.3 1.3 0 10-2.6 0v5.316H2.885a1.3 1.3 0 000 2.6H8.2v5.315a1.3 1.3 0 002.6 0v-5.315h5.315a1.3 1.3 0 100-2.6H10.8V2.452z"
                      clipRule="evenodd"
                    ></path>
                  </svg>
                  {PersonalConst[item]}
                </div>
              );
            })}
          </div>
        </div>
        <BottomButton
          loading={loading}
          onCancel={() => {
            onChangeCurrent?.();
            reset();
          }}
          onConfirm={async () => {
            const formData = await form.validateFields();
            let res;
            try {
              if (personalDetails.id) {
                setLoading(true);
                res = await serverStore.updatePersonalDetailFn(personalDetails);
                setLoading(false);
              } else {
                setLoading(true);
                res = await serverStore.saveAll();
                setLoading(false);
              }
            } catch {
              setLoading(false);
            }
            // onChangeCurrent?.()
            // updatePersonalDetail({})
          }}
        />
      </div>
    </StyleProvider>
  );
};

export default memo(Index);
